<template>
  <div class="hello">
    <mchat
      ref="mchat"
      :config="config"
      :chats="chats"
      :mine="mine"
      @chatEvent="handleChatEvent"
      @talkEvent="talkEvent"
      @sendMessage="sendMessage"
      @loadHistory="handleHistory"
      @uploadEvent="handleUpload"
    >
      <mchat-right-box>
        <template slot-scope="props">
          <mchat-group-list
            v-if="props.chat.type == 'group'"
            :notices="props.chat.notices"
            :userList="props.chat.userList"
            :filter-user-method="filterUser"
            @click="handleRightEvent"
          ></mchat-group-list>
          <div v-else>发挥你的想象</div>
        </template>
      </mchat-right-box>
    </mchat>
  </div>
</template>

<script>
  const img = "https://e-learning-lofxve.oss-cn-beijing.aliyuncs.com/2021/02/20/f6571a35edf54068907b23f70f0c4b69file.png"
  // 用户列表
  // const user_list = [
  //   {
  //     id: 1,
  //     name: "七月",
  //     online: true,
  //     type: "",
  //     avatar: "",
  //     role: 'master'
  //   },
  //   {
  //     id: 1,
  //     name: "初音",
  //     online: true,
  //     type: "",
  //     avatar: img,
  //     role: 'manager'
  //   },
  //   {
  //     id: 2,
  //     name: "雪",
  //     online: false,
  //     type: "",
  //     avatar: img,
  //     role: 'manager'
  //   },
  //   {
  //     id: 3,
  //     name: "可可罗",
  //     online: false,
  //     type: "",
  //     avatar: img,
  //   },
  //   {
  //     id: 4,
  //     name: "栞",
  //     online: false,
  //     type: "",
  //     avatar: img,
  //   },
  // ];

  // 历史记录
  const history = [
    {
      username: "历史记录",
      avatar: img,
      id: 1,
      type: "group",
      content: "audio[https://www.w3school.com.cn/i/horse.mp3]",
      cid: 0,
      mine: false,
      fromid: 3,
      timestamp: new Date(),
    },
  ];

  //  测试发送数据
  const test_send_msg = [
    {
      username: "小白",
      avatar: img,
      id: 1,
      type: "group",
      content: "img[/emoticon/emoticon_1.jpg]",
      cid: 0,
      mine: false,
      fromid: 2,
      timestamp: new Date(),
    },
    {
      username: "小奶",
      avatar: img,
      id: 1,
      type: "group",
      content: "video[https://www.w3school.com.cn/i/movie.mp4]",
      cid: 0,
      mine: false,
      fromid: 3,
      timestamp: new Date(),
    },
    {
      username: "老八",
      avatar: img,
      id: 1,
      type: "group",
      content: "audio[https://www.w3school.com.cn/i/horse.mp3]",
      cid: 0,
      mine: false,
      fromid: 3,
      timestamp: new Date(),
    },
  ]

  // const mine = {
  //   // 昵称
  //   username: "七月",
  //   // 用户id
  //   id: "10001",
  //   //状态
  //   status: "online",
  //   //签名
  //   sign: "与其感慨路难行,不如马上出发！",
  //   avatar: img,
  // }

  // const chats = [
  //
  //   {
  //     id: 1,
  //     name: "海喵突基队",
  //     type: "group",
  //     avatar: img,
  //     userList: user_list,
  //     master: 1
  //   },
  //   {
  //     id: -1,
  //     name: "系统消息",
  //     type: "sys_msg",
  //     online: false,
  //   },
  //   {
  //     id: 2,
  //     name: "初音",
  //     type: "friend",
  //     online: true,
  //     avatar: img,
  //   },
  //   {
  //     id: 3,
  //     name: "雪爷",
  //     type: "friend",
  //     online: false,
  //     avatar: img,
  //   },
  // ]

  import im from '../../api/im'

  const id = "607d46b94cc5d472abe86a50"
  export default {
    name: "i-chat-test",
    data() {
      return {
        //获取主面板列表信息，下文会做进一步介绍
        config: {
          // 是否有下拉按钮
          downBtn: true,
          rightBox: true,
          // 简约模式
          brief: true,
          // 是否开启桌面消息提醒，即在浏览器之外的提醒
          notice: false,
          // 设定
          voice: true,
          //上传文件的扩展名
          fileExt: "",
          tabRemove: false,
          fixed: false,
        },
        //我的信息
        mine: {},
        //会话
        // chats: chats,
        chats: [],
        userId: id,
        // 历史记录查询条件
        HistoryMessageQuery: {
          fromId: "",
          messageSize: 0,
          toId: "",
          type: "",
        },
        history: []
      };
    },
    methods: {
      // 查询会话列表
      getGroupsByUserId() {
        im.getGroupsByUserId(this.userId).then(response => {
          this.chats = response.data.data.chatVoArrayList
        })
      },
      // 根据id获取用户
      getMineById() {
        im.getMineById(this.userId).then(response => {
          this.mine = response.data.data.mine
          this.mine.username = this.mine.name
        })
      },
      // 发送消息
      saveMessage(message) {
        // message.id = null;
        im.saveMessage(message).then(response => {
          // console.log(response.data)
          // 界面更新消息
          this.$refs.mchat.getMessage(message);
        }).catch(error => {

        })
      },
      filterUser(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      fetchNotices() {
        let list = CONST.notice_list;
        return list;
      },
      handleChatEvent(event, data) {
        console.log("窗口事件", {event, data})
        let channels = this.chats;
        let len = channels.length;
        if (len < 1) return;
        let ary = [];
        switch (event) {
          case "removeChat":
            for (let i = 0; i < len; i++) {
              let model = channels[i];
              if (model.id != data.id) {
                ary.push(model);
              }
            }
            this.chats = ary;
            break;
        }
      },
      handleRightEvent(event) {
        console.log("右边框事件", event);
      },
      handleHistory(data) {
        const {chat, last, callback} = data;
        this.HistoryMessageQuery.fromId = this.mine.id
        this.HistoryMessageQuery.toId = data.chat.id
        this.HistoryMessageQuery.type = data.chat.type
        // 获取历史记录
        im.getHistoryMessage(this.HistoryMessageQuery).then(response => {
          let messages = response.data.data.messages
          // 如果获取的历史记录中了新的消息记录，则更新历史记录
          if (messages.length > chat.messageSize) {
            this.history = messages.slice(chat.messageSize)
            chat.messageSize = messages.length
          }
          callback(this.history);
        })
      },
      talkEvent(event, data) {
        console.log("谈话内容", {event, data});
      },
      sendMessage(data) {
        console.log("发送内容", {data});
        const {mine, to, content, timestamp} = data;
        let message = {
          //消息来源用户名
          username: mine.username,
          //消息来源用户头像
          avatar: mine.avatar,
          //消息的来源ID（如果是私聊，则是用户id，如果是群聊，则是群组id）
          id: to.id,
          //聊天窗口来源类型，从发送消息传递的to里面获取
          type: to.type,
          //消息内容
          content,
          //消息id，可不传。除非你要对消息进行一些操作（如撤回）
          toid: to.id,
          //是否我发送的消息，如果为true，则会显示在右方
          mine: true,
          //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
          fromid: mine.id,
          //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
          timestamp,
        };
        // 发送消息
        this.saveMessage(message)

        //自动回复
        // let authReplay = {
        //   username: "july-meteor",
        //   avatar: require("../../public/avatar/heiqi.png"),
        //   id: to.id,
        //   type: to.type,
        //   content: replay[(Math.random() * 9) | 0],
        //   cid: 0,
        //   mine: false,
        //   fromid: -1,
        //   timestamp: new Date(),
        // };
        // this.$im.emit("getMessage", authReplay);
      },
      //添加回话
      handleAddChat() {
        let chatId = parseInt(Math.random() * 10, 10)
        let newChat = {
          id: chatId,
          name: "新会话",
          type: "friend",
          avatar: require("../../public/avatar/temp2.jpg"),
        };
        this.chats.push(newChat);
      },
      handleDelChat() {
        this.chats.pop();
      },
      handleUpload(data, fn) {
        console.log("文件上传", data)

      }
    },
    created() {
      this.getGroupsByUserId()
      this.getMineById()
      // this.userId = this.$route.params.id;
      // console.log(this.$route.params.id)
    }
  };
</script>

<!--<style lang="scss">-->
<!--  .demo-box {-->
<!--    border: 1px solid #ebeef5;-->
<!--    background-color: #fff;-->
<!--    color: #303133;-->
<!--    transition: .3s;-->
<!--    border-radius: 4px;-->
<!--    overflow: hidden;-->
<!--    .demo-header {-->
<!--      padding: 18px 20px;-->
<!--      border-bottom: 1px solid #ebeef5;-->
<!--      box-sizing: border-box;-->
<!--      .demo-title {-->
<!--      }-->
<!--    }-->
<!--    .demo-body {-->
<!--      padding: 20px;-->

<!--    }-->

<!--  }-->
<!--</style>-->

